package logic

import (
	"github.com/gin-gonic/gin"
	"iot-base/auth/api/logic/platformmanager"
	"iot-base/auth/svc"
	"iot-base/auth/types"
)

func QueryReData(c *gin.Context) {
	requestId, _ := c.Get("RequestId")
	resp := types.NewResult(c)
	var qr types.QueryReData
	if err := c.ShouldBind(&qr); err != nil {
		resp.ErrorCode(types.Fail, err.Error())
		return
	}
	datas, err := svc.Dao.TReData.FindByModel(qr.ID)
	if err != nil {
		resp.ErrorCode(types.Fail, err.Error())
		return
	}
	resp.Success(gin.H{"requestId": requestId, "data": datas})
}

func QueryReDataByStyle(c *gin.Context) {
	requestId, _ := c.Get("RequestId")
	resp := types.NewResult(c)
	var qr types.QueryReDataByStyle
	if err := c.ShouldBind(&qr); err != nil {
		resp.ErrorCode(types.Fail, err.Error())
		return
	}
	datas, err := svc.Dao.TReData.FindByType(qr.ID, qr.Style)
	if err != nil {
		resp.ErrorCode(types.Fail, err.Error())
		return
	}
	resp.Success(gin.H{"requestId": requestId, "data": datas})
}

func ReportReData(c *gin.Context) {
	requestId, _ := c.Get("RequestId")
	resp := types.NewResult(c)
	var retime types.ReportReData
	if err := c.ShouldBind(&retime); err != nil {
		resp.ErrorCode(types.Fail, err.Error())
		return
	}
	platform, err := svc.Dao.TPlatform.FindById(retime.ID)
	if err != nil {
		resp.ErrorCode(types.Fail, err.Error())
		return
	}
	redatas, err := svc.Dao.TReData.FindByTime(retime.ID, retime.StartTime, retime.EndTime)
	if err != nil {
		resp.ErrorCode(types.Fail, err.Error())
		return
	}
	if _, ok := platformmanager.PlatformMap[retime.ID]; ok {
		err = platformmanager.ProtocolMap[platform.ProtocolName].SendReData(redatas)
		if err != nil {
			resp.ErrorCode(types.Fail, err.Error())
			return
		}
		err = svc.Dao.TReData.DelData(redatas)
		if err != nil {
			resp.ErrorCode(types.Fail, err.Error())
			return
		}
	}
	resp.Success(gin.H{"RequestId": requestId, "result": "ok"})
}
